package ejb.dao;


import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import ejb.entity.User;

@Stateless
public class DefaultUserDAO implements UserDAO{
	@PersistenceContext
	EntityManager em;	
	
    public DefaultUserDAO() {}    

    @Override
    public User create(User u){
    	try{
    		em.persist(u);
    	}catch(IllegalArgumentException e){
    		return null;
    	}
    	return u;    
    }
    
	@SuppressWarnings("unchecked")
	@Override
	public List<User> getUsers(){
		List<User> u = em.createNamedQuery("DefaultUser.findAll").getResultList();
		return u;
	}
	
	@Override
	public User getUserByLogin(String l){
		try{
			User u = (User) em.createNamedQuery("DefaultUser.findByLogin").setParameter("login", l).getSingleResult();
			return u;
		}catch(NoResultException e){
			return null;
		}catch(IllegalArgumentException e){
			return null;
		}		
	}	
	
	@Override
	public User getUserByCode(String code){
		try{
			User u = (User) em.createNamedQuery("DefaultUser.findByCode").setParameter("code", code).getSingleResult();
			return u;
		}catch(NoResultException e){
			return null;
		}catch(IllegalArgumentException e){
			return null;
		}
	}
		
	
	@Override
	public boolean delete(User u){
		try{
			em.remove(u);
		}catch(IllegalArgumentException e){
			return false;
		}
		return true;
	}
	
}
